package edu.dayu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.io.*;
import java.util.*;

public class TxtJson {
    public static void main(String[] args) throws IOException {
        String filePath = "C:\\Users\\86134\\Desktop\\rgxf2.txt";
        System.out.println(readFile(filePath));
    }

    /**
     * 读取txt文件，返回json字符串
     * @param filePath
     * @return
     */
    public static String readFile(String filePath){
        List<String> list = new ArrayList<>();
        Map<String,String> map = new LinkedHashMap<>();
        try {
            FileReader fileReader = new FileReader(filePath);
            BufferedReader reader = new BufferedReader(fileReader);
            String line;
            while((line = reader.readLine()) != null){
                list.add(transfer(line));
            }
            map.put("total",list.size()+"");
            map.put("recArr",list.toString());
            String s = JSON.toJSONString(map).replace("\\", "");
            map.clear();
            map.put("head",head());
            map.put("body",s);
            reader.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return JSON.toJSONString(map).replace("\\","");
    }

    /**
     * 将一行数据转化为json字符串
     * @param line
     * @return
     */
    public static String transfer(String line){
        String[] split = line.split(",");
        Map<String,String> map = new LinkedHashMap<>();
        map.put("lasttotalall",split[0]);
        map.put("valvst",split[1].equals("1")?"00":"10");
        map.put("battery",split[2]);
        map.put("rssi",split[3]);
        map.put("mdate",split[4]);
        map.put("meterno",split[5]);
        String json =JSONArray.toJSONString(map);;
        return json;
    }

    /**
     * 生成JSON头部
     * @return
     */
    public static String head(){
        Map<String,String> map = new LinkedHashMap<>();
        map.put("result","true");
        map.put("code","0");
        map.put("msg","成功");
        return JSON.toJSONString(map);
    }
}
